package br.com.saojose.main;

import java.util.Arrays;

import br.com.saojose.db.Database;
import br.com.saojose.model.Onibus;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListaDeOnibus extends ListActivity {
	
	String[] BUS_LIST;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);
		  loadAllBus();
		  
		  setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, BUS_LIST));
		  ListView lv = getListView();
		  lv.setTextFilterEnabled(true);
		  lv.setOnItemClickListener(new OnItemClickListener() {
		  
	      public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		      // When clicked, show a toast with the TextView text
		      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
		          Toast.LENGTH_SHORT).show();
		      
		      try {
			    	Intent intent = new Intent();
			      	intent.putExtra("bus_selected", ((TextView) view).getText());
			      	setResult(RESULT_OK, intent);
			      	finish();
		      } catch (Exception ex) {
		    	  Log.e("Lancou excecao", "LANCOU EXCEPTION");
		    	  Intent intent = new Intent();
			      	intent.putExtra("bus_selected", "nenhum onibus selecionado");
			      	setResult(RESULT_CANCELED, intent);
			      	finish();
		      }
		      
		    }
		  });
	}

	
	private void loadAllBus() {
		  BUS_LIST = new String[Database.getListaOnibus().size()];
		  int i = 0;
		  for (Onibus o : Database.getListaOnibus()) {
			  BUS_LIST[i] = o.getNumero().toString();
			  i++;
		  }
		  System.out.println(Arrays.toString(BUS_LIST));
	}
	
}
